package com.wyb.controller.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wyb.entity.User;
import com.wyb.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/register")
public class UserRegisterServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String mobile=req.getParameter("mobile");
        String sex=req.getParameter("sex");
        int age=Integer.parseInt(req.getParameter("age"));
        String description=req.getParameter("description");
        String code = req.getParameter("code");
        Map<String,Object> map=new HashMap<>();
        HttpSession session = req.getSession();
        boolean b=false;
        String str="";
        if(((String)session.getAttribute("code")).equalsIgnoreCase(code)){
            try {
                b=new UserServiceImpl().register(new User(null,username,password,mobile,sex,age,description));
            } catch (Exception e) {
                str=e.getMessage();
            }
        }else {
            str="验证码错误";
        }
        map.put("register",b);
        map.put("msg",str);
        PrintWriter pw = resp.getWriter();
        pw.println(new ObjectMapper().writeValueAsString(map));
        pw.flush();
    }
}
